# Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""
box_ops for VisTR
"""

import mindspore
from mindspore import Tensor, ops, nn
from mindspore.ops import operations as P


class CxcywhToXyxy(nn.Cell):
    """CxCyWH_to_XYXY

    Args:
        x(tensor):last dimension is four

    Returns:
        Tensor, last dimension is four
    """

    def __init__(self):
        super(CxcywhToXyxy, self).__init__()
        self.unstack = P.Unstack(axis=-1)
        self.stack = P.Stack(axis=-1)

    def construct(self, x):
        x_c, y_c, w, h = self.unstack(x)
        b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
             (x_c + 0.5 * w), (y_c + 0.5 * h)]
        out = self.stack(b)
        return out


class MultiIou(nn.Cell):
    """multi_iou.calculating Iou between pred boxes and gt boxes

    Args:
        out_bbox(tensor):predicted bbox
        tgt_bbox(tensor):Ground Truth

    Returns:
        Tensor, iou of two box
    """

    def __init__(self):
        super(MultiIou, self).__init__()
        self.max = P.Maximum()
        self.min = P.Minimum()
        self.max_value = Tensor(8388608, mindspore.float32)
        self.min_value = Tensor(0, mindspore.float32)

    def construct(self, out_bbox, tgt_bbox):
        """construct calculating iou"""
        lt = self.max(out_bbox[..., :2], tgt_bbox[..., :2])
        rb = self.min(out_bbox[..., 2:], tgt_bbox[..., 2:])
        wh = ops.clip_by_value((lt-rb), self.min_value, self.max_value)
        wh_1 = out_bbox[..., 2:] - out_bbox[..., :2]
        wh_2 = tgt_bbox[..., 2:] - tgt_bbox[..., :2]
        inter = wh[..., 0] * wh[..., 1]
        union = wh_1[..., 0] * wh_1[..., 1] + wh_2[..., 0] * wh_2[..., 1]
        union = union - inter
        iou = (inter+1e-6) / (union+1e-6)
        return iou
